<template>
	<view>
		<button @click="connectWifi(ip,port)">WiFi连接</button>
		<button @click="senBleLabel">WiFi打印</button>
		<!-- <button @click="test('test',ip,port)">WiFi打印2</button> -->
		<!-- <button @click="barCoder.printImage">生成图片</button> -->
		<!-- <view class="label" id="box">
			<u-row>
				<u-col span="12">
					<view class="label-row">
						<image :src="logo" mode="widthFix" class="label-logo"></image>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">ORDER NO：</text>
						<text class="label-value p-r-10">测试</text>
					</view>
				</u-col>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">Inbound Date：</text>
						<text class="label-value">测试</text>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">Ind Ser.No：</text>
						<text class="label-value p-r-10">测试</text>
					</view>
				</u-col>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">LOT&nbsp;NO：</text>
						<text class="label-value">测试</text>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">PN：</text>
						<text class="label-value p-r-10">测试</text>
					</view>
				</u-col>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">BOX NO：</text>
						<text class="label-value">测试</text>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">SN：</text>
						<text class="label-value p-r-10">测试</text>
					</view>
				</u-col>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">CERT：</text>
						<text class="label-value">测试</text>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">QTY：</text>
						<text class="label-value p-r-10">1 个</text>
					</view>
				</u-col>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">Manufacture Date：</text>
						<text class="label-value">测试</text>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">DESC：</text>
						<text class="label-value p-r-10">测试</text>
					</view>
				</u-col>
				<u-col span="6">
					<view class="label-row2">
						<text class="label-header">Life Limited Part：</text>
						<text class="label-value">测试</text>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="6">
					<view class="label-row2">
						<view class="label-title-box">
							<view>INSPECTOR：</view>
							<view class="label-title-banner">(STAMP)</view>
						</view>
						<text class="label-value-box"></text>
					</view>
				</u-col>
				<u-col span="6">
					<view>
						<view class="label-row2">
							<text class="label-header">Time Controlled：</text>
							<text class="label-value">测试</text>
						</view>
						<view class="label-row2">
							<text class="label-header">Next Insp.Date：</text>
							<text class="label-value">测试</text>
						</view>
						<view class="label-row2">
							<text class="label-header">Expire Date：</text>
							<text class="label-value">测试</text>
						</view>
					</view>
				</u-col>
			</u-row>
			<u-row>
				<u-col span="5">
					<view class="label-code">
						二维码
					</view>
				</u-col>
				<u-col span="7" :offset="1">
					<view class="label-code-title-box">
						<view class="label-code-title">测试</view>
						<view class="label-code-link">http://www.hangruntech.com/</view>
					</view>
				</u-col>
			</u-row> -->
		<!-- </view> -->
			<view class="canvasBox">
				<canvas :style="{width: canvasWidth +'px', height: canvasHeight +'px',opacity:0}"
					canvas-id="firstCanvas" id="firstCanvas" class="firstCanvas" />
				<image class="canvasImage" :src="canvasURL" mode="widthFix"></image>
			</view>
		</view>
</template>


<script>
	import tsc from "@/static/libs/tsc.js";
	import wifiTool from "@/static/libs/WifiTool.js";
	// 四舍五入
	function roundToNearestTen(num) {  
	  let lastDigit = num % 10;  
	  if (lastDigit > 5) {  
	    num = Math.round(num / 10) * 10 + 10;  
	  } else if (lastDigit < 5) {  
	    num = Math.round(num / 10) * 10;  
	  } else {  
	    num = num; // 最后一位数字刚好为5时，保持不变  
	  }  
	  return num;  
	}  
	export default {
		data() {
			return {
				ip: "192.168.16.134",
				port: 9100,
				str: "yyy",
				// canvasWidth: 1354,
				// canvasHeight: 374,
				canvasWidth: 375, //显示
				canvasHeight: 262, //显示
				canvasURL:'',
				logo: require('@/static/logo.png'),
			};
		},
		mounted() {
			wifiTool.connectWifi("192.168.16.134", 9100);
			// 生成图片
			this.$nextTick(()=>{
				this.renderCanvas();
			})
			// 生成logo
			// this.createLogo();
		},
		methods: {
			test(str, ip, port) {
				str = "test";
				var Socket = plus.android.importClass("java.net.Socket");
				var JavaByte = plus.android.importClass("java.lang.Byte");
				var PrintWriter = plus.android.importClass("java.io.PrintWriter");
				var BufferedWriter = plus.android.importClass("java.io.BufferedWriter");
				var OutputStreamWriter = plus.android.importClass("java.io.OutputStreamWriter");
				var BufferedReader = plus.android.importClass("java.io.BufferedReader");
				var InputStreamReader = plus.android.importClass("java.io.InputStreamReader");

				//测试改良
				var StrictMode = plus.android.importClass("android.os.StrictMode");
				var Build = plus.android.importClass("android.os.Build");
				if (Build.VERSION.SDK_INT > 9) {
					var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
					StrictMode.setThreadPolicy(policy);
				}
				var socket = new Socket(ip, port);

				var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
				var bufferWriter = new BufferedWriter(outputStreamWriter);
				var out = new PrintWriter(bufferWriter, true);

				var command = tsc.jpPrinter.createNew();
				command.init(0, 200, 200, 210, 1);
				command.setCls();
				command.setQR(30, 40, 2, 6, "123");
				//   command.setMag(2, 2);
				//   command.setText1(55, 30, 180, 60, "地址： 内蒙");
				//   command.setMag(2, 2);
				//   command.setText1(55, 6, 180, 120, "重量： 15kg");
				command.setPagePrint();
				let data = command.getData();

				out.println(data);
				socket.setSoTimeout(3000);
				socket.close();
			},
			printSocket() {
				// 可用
				//    var command = tsc.jpPrinter.createNew();
				//    command.init(0, 200, 250, 210, 1);
				//    command.setCls();
				//    command.setQR(30, 40, 2, 6, "123");
				//    command.setMag(2, 2);
				//    command.setText1(55, 30, 180, 60, "地址： 内蒙");
				//    command.setMag(2, 2);
				//    command.setText1(55, 6, 180, 120, "重量： 15kg");
				//    command.setPostfeed(32);//打印后走纸
				//    command.setPagePrint();
				//    let data = command.getData();
				// console.log('进入打印')
				//    wifiTool.sendData(data);

				//测试 
				var command = tsc.jpPrinter.createNew()
				command.init(0, 200, 250, 210, 1)
				// command.setSize(120, 200)
				command.setGap(3)
				command.setCls();
				command.setDensity(4);
				command.setText(50, 10, "TSS24.BF2", 1, 1, "打印测试")
				command.setQR(50, 50, "L", 5, "A", "https://www.baidu.com")
				// command.setBox(100, 100, 700, 500, 1)
				command.setPostfeed(80); //打印后走纸
				command.setPagePrint()
				let data = command.getData()
				// console.log(data, '这个')
				console.log('发送完毕')
				wifiTool.sendData(data);
			},
			senBleLabel() {
				//标签模式
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				const that = this;
				uni.canvasGetImageData({
					canvasId: 'firstCanvas',
					x: 0,
					y: 0,
					width: that.canvasWidth,
					height: that.canvasHeight,
					// width: 800,
					// height: 560,
					success: (res) => {
						// console.log('进入', res)
						console.log('进入', that.canvasWidth + "--" + that.canvasHeight)
                         // return 
                        // return
						var command = tsc.jpPrinter.createNew()
						command.init()
						command.setSize(100, 70)
						command.setGap(2)
						command.setCls();
						
						// command.setText(50, 10, "TSS24.BF2", 1, 1, "打印测试")
						// command.setQR(50, 50, "L", 5, "A", "https://www.baidu.com")
						// 方式一
						command.setDensity(4);
						// command.setBitmap2(30, 0, 2, res) //这个是标准
						// 方式二
						// command.setDensity(2);
						command.setBitmap3(15, 0, 2, res)
						
						// command.setBox(100, 100, 700, 500, 1)
						command.setPagePrint()
						let data = command.getData()
						// console.log(data, '这个')
						// bluetoothTool.sendByteData(data)
						wifiTool.sendData(data);
						console.log('发送完毕')
						uni.hideLoading()
					},
					fail: function(res) {
						console.log(res)
					}
				})
			},
			// // 新
			senBleLabel2(){
			
				// command.init()
				// command.setSize(120, 60)
				// command.setGap(2)
				// command.setCls();
				// command.setDensity(4);
				// command.setText(1, 1,'1', 3, 3, "2");
				// command.setText(1, 120, '1', 3, 123, "2");
				// command.setText(120, 1, '1', 123, 3, "2");
				// command.setText(120, 80, '1', 123, 83, "2");
				
				// command.setText(50, 1, "TSS24.BF2", 1, 1, "标准字体")
				// command.setText(50, 1, 2, 100, 1, "小字体") //小2
				
				 // command.setBar(100, 50, "128",50,1,2,6,'00001234567890'); //条形码
				 
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				const that = this;
				uni.canvasGetImageData({
					canvasId: 'firstCanvas',
					x: 0,
					y: 0,
					width: that.canvasWidth,
					height: that.canvasHeight,
					// width: 423,
					// height: 387,
					success: (res) => {
						var command = tsc.jpPrinter.createNew()
						command.init()
						command.setSize('100 mm', '70 mm')
						command.setGap(2)
						command.setCls();
						command.setDensity(4);
						// command.setText(50, 10, "TSS24.BF2", 1, 1, "打印测试")
						// command.setQR(50, 50, "L", 5, "A", "https://www.baidu.com")
						command.setBitmap3(70, 0, 2, res)
						command.setText(290, 15, 5, 1.5, 1.5, "SERVICEABLE PART") //x轴,y轴,字体样式,字体宽,字体高,内容
						// command.setBox(100, 100, 700, 500, 1)
						command.setPagePrint();
						let data = command.getData()
						wifiTool.sendData(data);
						console.log('发送完毕')
						uni.hideLoading()
					},
					fail: function(res) {
						console.log(res)
					}
				})
			},
			connectWifi(ip, port) {
				if (plus.os.name == "Android") {
					console.log('进入连接')
					// plus.nativeUI.showWaiting("正在打印中。。。");
					var Socket = plus.android.importClass("java.net.Socket");
					var socket;
					var outputStream;
					//解决高低版本兼容
					var StrictMode = plus.android.importClass("android.os.StrictMode");
					var Build = plus.android.importClass("android.os.Build");
					if (Build.VERSION.SDK_INT > 9) {
						var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
						StrictMode.setThreadPolicy(policy);
					}
					try {
						socket = new Socket(ip, port);
						socket.setKeepAlive(true);
						outputStream = socket.getOutputStream();
						plus.android.importClass(outputStream);
						//   var bytes = plus.android.invoke(str, "getBytes", "gbk");
						uni.showToast({
							title: "wifi连接成功",
						});

						//   plus.nativeUI.closeWaiting();
					} catch (e) {
						console.log("网络连接超时，请重新连接！");
						//TODO handle the exception
						//   plus.nativeUI.closeWaiting();
					}
				}
			},
			renderCanvas() {
				this.$nextTick(() => {
					uni.showLoading({
						title:'生成标签...',
						mask:true
					})
					let filePath = require('@/static/label8.png');
					let that = this;
					const firstCanvas = uni.createCanvasContext('firstCanvas', this);
					// let scla = 0.37;
					// let scla = 0.25;
					// let scla = 0.36;
					// let scla = 0.36;
					let scla = 1;
					uni.getImageInfo({
						src: filePath,
						success(res) {
							// console.log(res.width + "--" + res.height,'开始')
							// that.canvasWidth = res.width * scla;
							// that.canvasHeight = res.height * scla;
							// console.log(that.canvasWidth + "--" + that.canvasHeight,'结果')
							// 标准
							that.canvasWidth = 800 * scla;
							that.canvasHeight = 560 * scla;
							
							// that.canvasWidth = 370;
							// that.canvasHeight = 260;
							
							// that.printWidth = that.canvasWidth;
							// that.printHeight = that.canvasHeight;
							// 
							 // let wid = parseInt(res.width * scla);
							 // let hei = parseInt(res.height * scla);
							// 
							// that.canvasHeight = 1484 * scla;
							// 
							// that.canvasWidth = 800 * scla;
							// that.canvasHeight = 560 * scla;
							// that.canvasWidth = roundToNearestTen(wid)+10;
							// that.canvasHeight = roundToNearestTen(hei)+20;
							
							firstCanvas.drawImage(filePath, 0, 0, that.canvasWidth, that.canvasHeight);
							firstCanvas.draw();
							that.$nextTick(() => { //获取画布像素数据
							  that.canvasURL = filePath || '';
							  console.log(that.canvasURL,'有图')
							  uni.hideLoading();
							})
						},
						fail(res) {
							console.log(res)
						}
					})
				})
			},
			// 打印回调
			printImageCallback(base64) {
				console.log('进入base64', base64)
				const firstCanvas = uni.createCanvasContext('firstCanvas', this);
				firstCanvas.drawImage(base64, 0, 0, this.canvasWidth, this.canvasHeight);
				firstCanvas.draw();
			},
			// 新 --------------------------------- 
			createLogo() {
				const that = this;
				let path = require('@/static/label-logo.jpg');
				const firstCanvas = uni.createCanvasContext('firstCanvas', this);
				plus.io.resolveLocalFileSystemURL(path, (entry) => {
					entry.file((file) => {
						let fileReader = new plus.io.FileReader()
						fileReader.readAsDataURL(file)
						fileReader.onloadend = (evt) => {
							let base64 = evt.target.result.split(",")[1]
							that.logo = 'data:image/png;base64,' + base64;
							// console.log(that.logo)
							firstCanvas.drawImage(that.logo, 0, 0, that.canvasWidth, that.canvasHeight);
							firstCanvas.draw();
						}
					})
				})
			},
		},
	};
</script>

// <script module="barCoder" lang="renderjs">
// 	import html2canvas from "@/static/libs/html2canvas.js";
// 	export default {
// 		methods: {
// 			//创建图片
// 			createImage() {
// 				const _this = this;
// 				return new Promise((resolve, reject) => {
// 					// _this.$ownerInstance.callMethod('showLoading');
// 					// clearTimeout(timer)
// 					setTimeout(() => {
// 						const element = document.getElementById("box");
// 						html2canvas(element, {
// 							dpi: 2000,
// 							// scale: window.devicePixelRatio * 2,
// 							scale:1,
// 							allowTaint: true,
// 							foreignObjectRendering: true,
// 							allowTaint: true, //开启跨域
// 							useCORS: true,
// 							scrollY: 0,
// 							scrollX: 0,
// 							// x: -4,
// 							// y: -3
// 							x:0,
// 							y:0
// 						}).then((canvas) => {
// 							var context = canvas.getContext('2d');
// 							// 【重要】关闭抗锯齿
// 							context.mozImageSmoothingEnabled = false;
// 							context.webkitImageSmoothingEnabled = false;
// 							context.msImageSmoothingEnabled = false;
// 							context.imageSmoothingEnabled = false;

// 							const base64 = canvas.toDataURL();
// 							// _this.$ownerInstance.callMethod('saveImag', imgUrl);
// 							resolve(base64)
// 							// timer = null;
// 						})
// 					}, 400);
// 				})
// 			},
// 			// 打印图片
// 			printImage() {
// 				this.createImage().then((base64) => {
// 					this.$ownerInstance.callMethod('printImageCallback', base64);
// 				})
// 			}
// 		}
// 	}
// </script>
<style lang="scss" scoped>
	#box {
		border: 1px solid red;
	}

	.m-t-20 {
		margin-top: 10rpx;
	}

	.m-l-20 {
		margin-left: 20rpx;
	}

	.p-r-10 {
		padding-right: 10rpx;
		box-sizing: border-box;
	}

	.label-flex-center {
		display: flex;
		align-items: center;
	}

	.label {
		background-color: #fff;
		padding: 20rpx;

		& .label-row {
			display: flex;
			align-items: center;

			& .label-logo {
				width: 180rpx;
			}

			& .label-title {
				font-size: 38rpx;
				font-weight: bold;
				margin-left: 20rpx;
			}
		}

		& .label-row2 {
			display: flex;
			align-items: flex-start;
			font-size: 24rpx;
			font-weight: bold;
			line-height: 50rpx;

			& .label-value {
				font-weight: 500;
				color: #333;
			}

			& .label-title-box {
				line-height: 50rpx;

				& .label-title-banner {
					// line-height: 20rpx;
				}
			}

			& .label-value-box {
				flex: 0.9;
				height: 100rpx;
				border: 1px solid #909399;
			}
		}

		& .label-code {
			// width: 90%;
		}

		& .label-code-title-box {
			& .label-code-title {
				font-size: 70rpx;
				font-weight: bold;
			}

			& .label-code-link {
				font-size: 26rpx;
				color: #333;
			}
		}

		& .label-header {
			white-space: normal;
			word-break: keep-all;
		}

		& .label-qty {
			width: 100rpx;
			height: 50rpx;
			line-height: 50rpx;
			font-size: 24rpx;

			& .input-placeholder {
				font-size: 24rpx;
				line-height: 50rpx;
			}
		}
	}

	::v-deep {
		.u-row {
			display: flex;
			align-items: flex-start !important;
		}
	}
	
	.canvasBox{
		width: 100%;
		height: 260px;
		border: 1px solid red;
		box-sizing: border-box;
		overflow: hidden;
		position: relative;
		& .canvasImage{
			width: 100%;
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
		}
	}
</style>